/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, {useEffect, useState} from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableOpacity,
  Dimensions,
  ImageBackground,
  LogBox,
} from 'react-native';
import Orientation from 'react-native-orientation';
import Slider from 'react-native-slider';
import {
  ExpandedRegionLayoutOptions,
  FoldedRegionLayoutOptions,
  FoldSplitContainer,
  HoverModeRegionLayoutOptions,
  PresetSplitRatio,
} from '@hadss/react_native_adaptive_layout/src';
import SampleTurboModule from '../basic/SampleTurboModule';
import Swiper from 'react-native-swiper';
import musicPlayer from '../util/index';

function MusicPlay() {
  const [playState, setPlayState] = useState<boolean>();
  const [position, setPosition] = useState<number>(0);
  const [duration, setDuration] = useState<number>(0);
  const [title, setTitle] = useState<string>();
  const [artist, setArtist] = useState<string>();
  const [isHover, setIsHover] = useState<boolean>(false);
  const [isExpanded, setIsExpanded] = useState<boolean>(
    Dimensions.get('window').width >= 600,
  );
  const isWide = Dimensions.get('screen').height >= 900 || Dimensions.get('screen').width >= 900;
  const [isLarge, setIsLarge] = useState<boolean>(
    Dimensions.get('window').width >= 800,
  );

  useEffect(() => {
    LogBox.ignoreAllLogs();
    isWide && Orientation.lockToLandscape();
    const screenListener = Dimensions.addEventListener('change', ({window: {width}}) => {
        setIsExpanded(width >= 600);
        setIsLarge(width >= 800);
      },
    );
    musicPlayer.onProgress((currentTime, duration) => {
      setPosition(currentTime / 1000);
      setDuration(duration / 1000);
    });
    updateTrack();
    musicPlayer.setOnTrackChange(() => {
      updateTrack();
    });
    return () => {
      screenListener.remove();
      isWide && Orientation.unlockAllOrientations();
    };
  }, [isWide]);

  const onLayout = event => {
    const {nativeEvent} = event;
    const {layout} = nativeEvent;
    setIsHover(layout.width > 600);
  };

  const togglePlayPause = async () => {
    const state = musicPlayer.getCurrentStatus();
    state ? musicPlayer.pause() : musicPlayer.play();
    setPlayState(!state);
  };

  const skipToNext = async () => {
    musicPlayer.nextTrack();
    updateTrack();
    setPlayState(true);
  };

  const skipToPrevious = async () => {
    musicPlayer.previousTrack();
    updateTrack();
    setPlayState(true)
  };

  const updateTrack = () => {
    const track = musicPlayer.getCurrentTrack();
    if (track) {
      setPlayState(musicPlayer.getCurrentStatus());
      setArtist(track.artist);
      setTitle(track.title);
    }
  };

  const seekTo = (val: number) => {
    musicPlayer.setCurrentTime(val * 1000);
  };

  const formatTime = (second: number) => {
    // 计算分钟数，注意 Math.floor 会向下取整
    const minutes = Math.floor(second / 60);
    // 计算剩余的秒数，使用 % 运算符取余数
    const remainingSeconds = Math.floor(second % 60);

    // 使用字符串的 padStart 方法来确保分钟和秒数都是两位数
    // 如果数字小于 10，则在前面添加一个 0
    const formattedMinutes = minutes.toString().padStart(2, '0');
    const formattedSeconds = remainingSeconds.toString().padStart(2, '0');

    // 返回格式化的时间字符串
    return `${formattedMinutes}:${formattedSeconds}`;
  };

  const backToLast = () => {
    SampleTurboModule.pushStringToHarmony('PlayListPage', 2);
  };

  const primaryRender = () => (
    <View style={{flex: 1, alignItems: 'center'}}>
      <Image
        source={require('../../../asset/artwork.png')}
        style={{
          aspectRatio: 1,
          height: '75%',
          marginTop: 100,
          borderRadius: 10,
        }}
      />
    </View>
  );

  const secondRender = () => (
    <View style={{flex: 1, alignItems: 'center'}} onLayout={onLayout}>
      <View
        style={{
          width: isHover ? '93%' : '88%',
          marginHorizontal: 20,
          alignItems: isHover ? 'flex-start' : 'center',
          marginTop: isHover ? 0 : 20,
        }}>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            width: isHover ? '36%' : '100%',
          }}>
          <View>
            <Text style={styles.title}>{title}</Text>
            <Text style={styles.artist}>{artist}</Text>
          </View>
          <Image
            source={require('../../../asset/likes.svg')}
            style={styles.imageGrey}
          />
        </View>
      </View>
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          width: isHover ? '93%' : '88%',
          marginTop: isHover ? 20 : 50,
        }}>
        <Slider
          style={{width: '100%'}}
          minimumValue={0}
          maximumValue={duration}
          value={position}
          minimumTrackTintColor="#e8e1e1"
          maximumTrackTintColor="#784949"
          thumbStyle={{opacity: 0, width: 0}}
          onValueChange={(val: number) => {
            seekTo(val);
          }}
        />
      </View>
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          width: isHover ? '93%' : '88%',
        }}>
        <Text style={styles.text}>{formatTime(position)}</Text>
        <Text style={styles.text}>{formatTime(duration)}</Text>
      </View>
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          width: isHover ? '93%' : '88%',
          alignItems: 'center',
          marginTop: 20,
        }}>
        <Image
          source={require('../../../asset/repeat.svg')}
          style={styles.imageGrey}
        />
        <TouchableOpacity onPress={skipToPrevious}>
          <Image
            source={require('../../../asset/left.svg')}
            style={styles.image}
          />
        </TouchableOpacity>
        <TouchableOpacity onPress={togglePlayPause}>
          <Image
            source={
              playState
                ? require('../../../asset/pause.svg')
                : require('../../../asset/play.svg')
            }
            style={styles.imagePlay}
          />
        </TouchableOpacity>
        <TouchableOpacity onPress={skipToNext}>
          <Image
            source={require('../../../asset/forward_end_fill.svg')}
            style={styles.image}
          />
        </TouchableOpacity>
        <Image
          source={require('../../../asset/music_note_list.svg')}
          style={styles.imageGrey}
        />
      </View>
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          width: isHover ? '93%' : '88%',
          alignItems: 'center',
          marginTop: 30,
        }}>
        <Image
          source={require('../../../asset/share_play.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/bell.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/arrow_down_circle.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/dot.svg')}
          style={styles.imageGrey}
        />
      </View>
    </View>
  );

  const secondPadRender = () => (
    <View style={{flex: 1, alignItems: 'center'}}>
      <View style={styles.message}>
        <View>
          <Text style={styles.title}>{title}</Text>
          <Text style={styles.artist}>{artist}</Text>
        </View>
        <Image
          source={require('../../../asset/likes.svg')}
          style={styles.imageGrey}
        />
      </View>
      <View style={styles.slider}>
        <Slider
          style={{width: '100%'}}
          minimumValue={0}
          maximumValue={duration}
          value={position}
          minimumTrackTintColor="#e8e1e1"
          maximumTrackTintColor="#784949"
          thumbStyle={{opacity: 0}}
          onValueChange={(val: number) => {
            seekTo(val);
          }}
        />
      </View>
      <View style={styles.controls}>
        <Text style={styles.text}>{formatTime(position)}</Text>
        <Text style={styles.text}>{formatTime(duration)}</Text>
      </View>
      <View style={styles.container}>
        <Image
          source={require('../../../asset/repeat.svg')}
          style={styles.imageGrey}
        />
        <TouchableOpacity onPress={skipToPrevious}>
          <Image
            source={require('../../../asset/left.svg')}
            style={styles.image}
          />
        </TouchableOpacity>
        <TouchableOpacity onPress={togglePlayPause}>
          <Image
            source={
              playState
                ? require('../../../asset/pause.svg')
                : require('../../../asset/play.svg')
            }
            style={styles.imagePlay}
          />
        </TouchableOpacity>
        <TouchableOpacity onPress={skipToNext}>
          <Image
            source={require('../../../asset/forward_end_fill.svg')}
            style={styles.image}
          />
        </TouchableOpacity>
        <Image
          source={require('../../../asset/music_note_list.svg')}
          style={styles.imageGrey}
        />
      </View>
      <View style={styles.container}>
        <Image
          source={require('../../../asset/share_play.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/bell.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/arrow_down_circle.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/dot.svg')}
          style={styles.imageGrey}
        />
      </View>
    </View>
  );

  const extraRender = () => (
    <View style={styles.extra}>
      <Text
        style={{
          marginTop: isHover ? 70 : 0,
          fontSize: 23,
          color: '#ffffff',
        }}>
        此歌曲为纯音乐，请您欣赏
      </Text>
    </View>
  );

  const extraPage = () => (
    <View style={styles.extra}>
      <View
        style={{
          flexDirection: 'row',
          position: 'absolute',
          height: '70%',
          width: '85%',
        }}>
        <Image
          source={require('../../../asset/artwork.png')}
          style={{
            width: 50,
            height: 50,
            borderRadius: 1,
          }}
        />
        <View>
          <Text
            style={{
              fontSize: 16,
              color: '#ffffff',
              margin: 5,
            }}>
            {title}
          </Text>
          <Text
            style={{
              fontSize: 12,
              color: '#ffffff',
              opacity: 0.4,
              margin: 5,
            }}>
            {artist}
          </Text>
        </View>
      </View>
      <Text
        style={{
          fontSize: 23,
          color: '#ffffff',
        }}>
        此歌曲为纯音乐，请您欣赏
      </Text>
    </View>
  );

  const expandedLayoutOptions: ExpandedRegionLayoutOptions = {
    isExtraRegionPerpendicular: true,
    verticalSplitRatio: PresetSplitRatio.LAYOUT_1V1,
    horizontalSplitRatio: 0.9,
  };

  const foldedRegionLayoutOptions: FoldedRegionLayoutOptions = {
    verticalSplitRatio: PresetSplitRatio.LAYOUT_1V1,
  };

  const hoverModeLayoutOptions: HoverModeRegionLayoutOptions = {
    horizontalSplitRatio: 0.66,
    showExtraRegion: true,
  };

  return (
    <ImageBackground
      source={require('../../../asset/blur.png')}
      style={{width: '100%', height: '100%'}}>
      <View
        style={{
          position: 'absolute',
          width: '100%',
          alignItems: 'center',
          zIndex: 1,
        }}>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            width: isExpanded ? '95%' : '88%',
            alignItems: 'center',
            marginTop: 40,
          }}>
          <TouchableOpacity onPress={backToLast}>
            <Image
              source={require('../../../asset/down.png')}
              style={styles.imageSmall}
            />
          </TouchableOpacity>
          <Image
            source={require('../../../asset/share.svg')}
            style={styles.imageSmall}
          />
        </View>
      </View>
      {isWide && isLarge && (
        <View style={{flex: 1, flexDirection: 'row'}}>
          <View style={styles.padLayout}>
            <View style={{flex: 1, alignItems: 'center'}}>
              <Image
                source={require('../../../asset/artwork.png')}
                style={styles.imageArtworkBig}
              />
            </View>
            {secondPadRender()}
          </View>
          <View style={{flex: 1}}>{extraRender()}</View>
        </View>
      )}
      {isWide && !isLarge && (
        <Swiper
          showsPagination={true}
          paginationStyle={styles.paginationStyle}
          loop={false}
          autoplay={false}
          dotStyle={styles.swiperDot}
          activeDotStyle={styles.activeDot}
          pagingEnabled={true}>
          <View style={styles.padLayout}>
            <View style={{flex: 1, alignItems: 'center'}}>
              <Image
                source={require('../../../asset/artwork.png')}
                style={styles.imageArtworkBig}
              />
            </View>
            {secondPadRender()}
          </View>
          {extraPage()}
        </Swiper>
      )}
      {!isWide && isExpanded && (
        <FoldSplitContainer
          primary={primaryRender()}
          secondary={secondRender()}
          extra={extraRender()}
          expandedLayoutOptions={expandedLayoutOptions}
          foldedLayoutOptions={foldedRegionLayoutOptions}
          hoverModeLayoutOptions={hoverModeLayoutOptions}
        />
      )}
      {!isWide && !isExpanded && (
        <Swiper
          showsPagination={true}
          paginationStyle={styles.paginationStyle}
          loop={false}
          autoplay={false}
          dotStyle={styles.swiperDot}
          activeDotStyle={styles.activeDot}
          pagingEnabled={true}>
          <FoldSplitContainer
            primary={primaryRender()}
            secondary={secondRender()}
            extra={extraRender()}
            expandedLayoutOptions={expandedLayoutOptions}
            foldedLayoutOptions={foldedRegionLayoutOptions}
            hoverModeLayoutOptions={hoverModeLayoutOptions}
          />
          {extraPage()}
        </Swiper>
      )}
    </ImageBackground>
  );
}

const styles = StyleSheet.create({
  trackInfo: {
    marginTop: 20,
  },
  title: {
    fontSize: 23,
    color: '#ffffff',
  },
  artist: {
    fontSize: 16,
    color: '#ffffff',
    opacity: 0.4,
  },
  slider: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: 300,
    marginTop: 20,
  },
  controls: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: 300,
  },
  container: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: 300,
    alignItems: 'center',
    marginTop: 20,
  },
  message: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: 300,
    alignItems: 'center',
    marginTop: 50,
  },
  padLayout: {
    flex: 1,
  },
  topIcon: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '93%',
    alignItems: 'center',
    marginTop: 40,
  },
  extra: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    color: 'white',
    opacity: 0.4,
    fontSize: 12,
  },
  image: {
    width: 40,
    height: 40,
  },
  imageSmall: {
    width: 25,
    height: 25,
  },
  imageNavi: {
    width: 32,
    height: 5,
  },
  imageGrey: {
    width: 30,
    height: 30,
    opacity: 0.4,
  },
  imagePlay: {
    width: 80,
    height: 80,
  },
  imageArtwork: {
    width: '88%',
    height: '78%',
    marginTop: '25%',
    borderRadius: 10,
  },
  imageArtworkBig: {
    aspectRatio: 1,
    height: 300,
    marginTop: '18%',
    borderRadius: 10,
  },
  paginationStyle: {
    height: 10,
    top: 50,
  },
  swiperDot: {
    backgroundColor: 'rgba(255,255,255,0.2)',
    width: 7,
    height: 6,
    borderRadius: 2,
    magin: 3,
  },
  activeDot: {
    backgroundColor: 'rgb(255,255,255)',
    width: 12,
    height: 6,
    borderRadius: 3,
    magin: 3,
  },
});

export default MusicPlay;
